﻿using Furion.DependencyInjection;
using Furion.InstantMessaging;
using Furion.TaskScheduler;
using FurionApiDemo.Core.Manager.User;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FurionApiDemo.Core.SignalRHub
{
    [MapHub("/signalRMessageHub")]
    public class SignalRMessageHub : Hub, ITransient
    {
        private readonly IUserManager _userManager; // 用户管理
        private readonly ISystemService _systemService;
        private readonly IUserService _userService;

        public SignalRMessageHub(IUserManager userManager, ISystemService systemService, IUserService userService)
        {
            _userManager = userManager;
            _systemService = systemService;
            _userService = userService;
        }
        // 其他代码

        public static void HttpConnectionDispatcherOptionsSettings(HttpConnectionDispatcherOptions options)
        {
            // 配置
        }

        public static void HubEndpointConventionBuilderSettings(HubEndpointConventionBuilder Builder)
        {
            // 配置
            Builder.RequireCors("any").RequireCors(t =>
            {
                t.WithOrigins("http://localhost:8001").AllowAnyMethod().AllowAnyHeader().AllowCredentials().Build();
            });
        }

        public override async Task OnConnectedAsync()
        {
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }


        /// <summary>
        /// 加入组
        /// </summary>
        /// <returns></returns>
        public async Task JoinGroup(string GroupName)
        {
            var _clients = Clients;
            if (!SpareTime.GetWorkers().Any(t => t.WorkerName == GroupName))
            {
                SpareTime.Do(1000, (timer, count) =>
                {
                    _clients.Group(GroupName).SendAsync("ReceiveMessage", _systemService.GetRunInfo());
                }, GroupName);
            }
            await Groups.AddToGroupAsync(Context.ConnectionId, GroupName);
            adminList.Add(Context.ConnectionId);
        }

        List<string> adminList = new List<string>();

        /// <summary>
        /// 退出组
        /// </summary>
        /// <param name="GroupName"></param>
        /// <returns></returns>
        public async Task LeaveGroup(string GroupName)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, GroupName);
            adminList.Remove(Context.ConnectionId);
            if (adminList.Count == 0)
            {
                SpareTime.Cancel(GroupName);
            }
        }

        // 定义一个方法供客户端调用
        public async Task SendMessage(string user, string message)
        {
            // 触发客户端定义监听的方法
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        public async Task SendMessageToGroup(string GroupName, string message)
        {
            await Clients.Group(GroupName).SendAsync("ReceiveMessage", message);
        }
    }
}
